package com.radish.framelibrary.view.glide;

import android.content.Context;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.radish.baselibrary.utils.LogUtils;
import com.radish.framelibrary.R;

/**
 * Created by xiaoMan on 2016/9/30.
 * details:
 * Glide 工具类
 * Google推荐的图片加载库，专注于流畅的滚动
 * <p/>
 * Glide 比Picasso  加载快 但需要更大的内存来缓存
 * <p/>
 * Glide 不光接受Context，还接受Activity 和 Fragment ,图片加载会和Activity/Fragment的生命周期保持一致 在onPause（）暂停加载，onResume（）恢复加载
 * <p/>
 * 支持GIF格式图片加载
 * <p>
 * GlideUtils.getInstance().LoadContextBitmap(mContext, urlPath,iv, R.drawable.shop_placeholder_loading, R.drawable.shop_placeholder_loadfail, null);
 */

public class GlideUtils {

    private static GlideUtils instance;
    private static RequestOptions requestOptions;
    private @DrawableRes
    int imgDefault = R.drawable.shape_rectangle_round_bg_gray;
    private @DrawableRes
    int imgCircleDefault = R.drawable.shape_oval_bg_gray;

    public static GlideUtils getInstance() {
        if (instance == null) {
            synchronized (GlideUtils.class) {
                if (instance == null) {
                    instance = new GlideUtils();
                    requestOptions = new RequestOptions();
                }
            }
        }
        return instance;
    }

    /**
     * 加载圆角图片
     *
     * @param context
     * @param path
     * @param corner
     * @param imageView
     */
    public void loadCornerImage(Context context, Object path, int corner, final ImageView imageView) {
        LogUtils.e("path:" + path);
        try {
            RoundedCorners roundedCorners = new RoundedCorners(corner);

            requestOptions = RequestOptions
                    .bitmapTransform(roundedCorners)
                    .placeholder(imgDefault)
                    .error(imgDefault)
                    .transform(new GlideRoundTransform(context, corner));
            if (path instanceof String && TextUtils.isEmpty((CharSequence) path)) {
                Glide.with(context).load(imgDefault).apply(requestOptions).into(imageView);
                return;
            }

            Glide.with(context).load(path).apply(requestOptions).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    imageView.setImageDrawable(resource);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载普通图片，有展位图和错误图
     *
     * @param context
     * @param path
     * @param imageView
     */
    public void loadNormalImage(Context context, Object path, ImageView imageView) {
        loadNormalImage(context, path, imageView, imgDefault);
    }

    /**
     * 加载普通图片，有展位图和错误图
     *
     * @param context
     * @param path
     * @param imageView
     */
    public void loadNormalImage(Context context, Object path, final ImageView imageView, int defaultImg) {
        try {
            if (path instanceof String)
                path = path.toString().replaceAll("\\\\", "");
            Glide.with(context).load(path).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    imageView.setImageDrawable(resource);
                }
            });
        } catch (Exception e) {
            LogUtils.e("e:" + e.toString());
            e.printStackTrace();
        }
    }

    /**
     * 加载普通图片，有展位图和错误图
     *
     * @param context
     * @param path
     * @param imageView
     */
    public void loadNormalImageNoCache(Context context, Object path, final ImageView imageView) {
        try {
            RequestOptions requestOptions = new RequestOptions()
                    .centerCrop()
                    .placeholder(imgDefault)
                    .error(imgDefault)
                    .skipMemoryCache(true) // 不使用内存缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE); // 不使用磁盘缓存

            if (path instanceof String && TextUtils.isEmpty((CharSequence) path)) {
                Glide.with(context).load(imgDefault).apply(requestOptions).into(imageView);
                return;
            }
            Glide.with(context).load(path).apply(requestOptions).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    imageView.setImageDrawable(resource);
                }
            });
        } catch (Exception e) {
            LogUtils.e("e:" + e.toString());
            e.printStackTrace();
        }
    }

    /**
     * 加载圆形图片
     *
     * @param context
     * @param path
     * @param imageView
     */
    public void loadCircleImage(final Context context, Object path, final ImageView imageView) {
        try {
            if (path instanceof String)
                path = path.toString().replaceAll("\\\\", "");

            final RequestOptions requestOptions = new RequestOptions()
                    .circleCrop()
                    .placeholder(imgCircleDefault)
                    .error(imgCircleDefault);

            if (path instanceof String && TextUtils.isEmpty((CharSequence) path)) {
                Glide.with(context).load(imgCircleDefault).apply(requestOptions).into(imageView);
                return;
            }
            Glide.with(context).load(path).apply(requestOptions).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    imageView.setImageDrawable(resource);
//                    Glide.with(context).load(resource).into(imageView);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            //noinspection ConstantConditions
            wm.getDefaultDisplay().getRealSize(point);
        } else {
            //noinspection ConstantConditions
            wm.getDefaultDisplay().getSize(point);
        }
        return point.x;
    }
}